package cn.sciento.dd.service.impl;

import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import cn.sciento.dd.constant.DingErrorCode;
import cn.sciento.dd.dto.TokenDTO;
import cn.sciento.dd.service.DingTokenService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class DingTokenServiceImpl implements DingTokenService {
  protected static final String DD_TOKEN_KEY = "hips:token:dd";
  
  @Resource(name = "wdRedisTemplate")
  protected RedisTemplate redisTemplate;
  
  @Resource(name = "wdRestTemplate")
  protected RestTemplate restTemplate;
  
  public TokenDTO getTokenWithCache(String appId, String appSecret) {
    String key = "hips:token:dd:" + appId;
    ValueOperations<String, TokenDTO> valueOperations = this.redisTemplate.opsForValue();
    if (this.redisTemplate.hasKey(key).booleanValue()) {
      TokenDTO tokenDTO1 = (TokenDTO)valueOperations.get(key);
      return tokenDTO1;
    } 
    TokenDTO tokenDTO = (TokenDTO)this.restTemplate.getForObject("https://oapi.dingtalk.com/gettoken?appkey=" + appId + "&appsecret=" + appSecret, TokenDTO.class);
    if (DingErrorCode.SUCCESS.intValue() == tokenDTO.getErrcode()) {
      int expires_in = tokenDTO.getExpires_in();
      valueOperations.set(key, tokenDTO);
      this.redisTemplate.expire(key, expires_in, TimeUnit.SECONDS);
    } 
    return tokenDTO;
  }
  
  public TokenDTO getToken(String appId, String appSecret) {
    return (TokenDTO)this.restTemplate.getForObject("https://oapi.dingtalk.com/gettoken?appkey=" + appId + "&appsecret=" + appSecret, TokenDTO.class);
  }
  
  public TokenDTO getTokenFromThirdPart(String authUrl) {
    return (TokenDTO)this.restTemplate.getForObject(authUrl, TokenDTO.class);
  }
}
